package com.lavender.async._async_response;

import com.lavender.async._common.ApiResponse;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.async.WebAsyncTask;

/**
 * <p>
 * WebAsyncTask异步响应
 * 使用场景：比Callable功能强大，能处理超时处理的回调或者错误处理的回调，因此就WebAsyncTask和Callable而言，多使用WebAsyncTask
 * 实现原理：
 * </p>
 *
 * @author: zhu.chen
 * @date: 2021/3/23
 * @version: v1.0.0
 */
@RestController
@RequestMapping("/webtask")
public class WebAsyncTaskResponse {

    /**
     * http://localhost:8086/async/webtask/hello
     */
    @GetMapping("hello")
    public WebAsyncTask<ApiResponse> hello() {
        WebAsyncTask<ApiResponse> task = new WebAsyncTask<ApiResponse>(() -> {
            return ApiResponse.instanceSuccessApiResponse("hello world");
        });
        task.onCompletion(() -> {
            System.out.println("调用结束啦！");
        });
        task.onTimeout(() -> {
            return ApiResponse.instanceFailApiResponse("超时了");
        });
        return task;
    }

}
